{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Trends and cycles in unemployment\n",
    "\n",
    "Here we consider three methods for separating a trend and cycle in economic data. Supposing we have a time series $y_t$, the basic idea is to decompose it into these two components:\n",
    "\n",
    "$$\n",
    "y_t = \\mu_t + \\eta_t\n",
    "$$\n",
    "\n",
    "where $\\mu_t$ represents the trend or level and $\\eta_t$ represents the cyclical component. In this case, we consider a *stochastic* trend, so that $\\mu_t$ is a random variable and not a deterministic function of time. Two of methods fall under the heading of \"unobserved components\" models, and the third is the popular Hodrick-Prescott (HP) filter. Consistent with e.g. Harvey and Jaeger (1993), we find that these models all produce similar decompositions.\n",
    "\n",
    "This notebook demonstrates applying these models to separate trend from cycle in the U.S. unemployment rate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import statsmodels.api as sm\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pandas_datareader.data import DataReader\n",
    "endog = DataReader('UNRATE', 'fred', start='1954-01-01')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Hodrick-Prescott (HP) filter\n",
    "\n",
    "The first method is the Hodrick-Prescott filter, which can be applied to a data series in a very straightforward method. Here we specify the parameter $\\lambda=129600$ because the unemployment rate is observed monthly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hp_cycle, hp_trend = sm.tsa.filters.hpfilter(endog, lamb=129600)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Unobserved components and ARIMA model (UC-ARIMA)\n",
    "\n",
    "The next method is an unobserved components model, where the trend is modeled as a random walk and the cycle is modeled with an ARIMA model - in particular, here we use an AR(4) model. The process for the time series can be written as:\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "y_t & = \\mu_t + \\eta_t \\\\\n",
    "\\mu_{t+1} & = \\mu_t + \\epsilon_{t+1} \\\\\n",
    "\\phi(L) \\eta_t & = \\nu_t\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "where $\\phi(L)$ is the AR(4) lag polynomial and $\\epsilon_t$ and $\\nu_t$ are white noise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mod_ucarima = sm.tsa.UnobservedComponents(endog, 'rwalk', autoregressive=4)\n",
    "# Here the powell method is used, since it achieves a\n",
    "# higher loglikelihood than the default L-BFGS method\n",
    "res_ucarima = mod_ucarima.fit(method='powell', disp=False)\n",
    "print(res_ucarima.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Unobserved components with stochastic cycle (UC)\n",
    "\n",
    "The final method is also an unobserved components model, but where the cycle is modeled explicitly.\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "y_t & = \\mu_t + \\eta_t \\\\\n",
    "\\mu_{t+1} & = \\mu_t + \\epsilon_{t+1} \\\\\n",
    "\\eta_{t+1} & = \\eta_t \\cos \\lambda_\\eta + \\eta_t^* \\sin \\lambda_\\eta + \\tilde \\omega_t \\qquad & \\tilde \\omega_t \\sim N(0, \\sigma_{\\tilde \\omega}^2) \\\\\n",
    "\\eta_{t+1}^* & = -\\eta_t \\sin \\lambda_\\eta + \\eta_t^* \\cos \\lambda_\\eta + \\tilde \\omega_t^* & \\tilde \\omega_t^* \\sim N(0, \\sigma_{\\tilde \\omega}^2)\n",
    "\\end{align}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mod_uc = sm.tsa.UnobservedComponents(\n",
    "    endog, 'rwalk',\n",
    "    cycle=True, stochastic_cycle=True, damped_cycle=True,\n",
    ")\n",
    "# Here the powell method gets close to the optimum\n",
    "res_uc = mod_uc.fit(method='powell', disp=False)\n",
    "# but to get to the highest loglikelihood we do a\n",
    "# second round using the L-BFGS method.\n",
    "res_uc = mod_uc.fit(res_uc.params, disp=False)\n",
    "print(res_uc.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Graphical comparison\n",
    "\n",
    "The output of each of these models is an estimate of the trend component $\\mu_t$ and an estimate of the cyclical component $\\eta_t$. Qualitatively the estimates of trend and cycle are very similar, although the trend component from the HP filter is somewhat more variable than those from the unobserved components models. This means that relatively mode of the movement in the unemployment rate is attributed to changes in the underlying trend rather than to temporary cyclical movements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(2, figsize=(13,5));\n",
    "axes[0].set(title='Level/trend component')\n",
    "axes[0].plot(endog.index, res_uc.level.smoothed, label='UC')\n",
    "axes[0].plot(endog.index, res_ucarima.level.smoothed, label='UC-ARIMA(2,0)')\n",
    "axes[0].plot(hp_trend, label='HP Filter')\n",
    "axes[0].legend(loc='upper left')\n",
    "axes[0].grid()\n",
    "\n",
    "axes[1].set(title='Cycle component')\n",
    "axes[1].plot(endog.index, res_uc.cycle.smoothed, label='UC')\n",
    "axes[1].plot(endog.index, res_ucarima.autoregressive.smoothed, label='UC-ARIMA(2,0)')\n",
    "axes[1].plot(hp_cycle, label='HP Filter')\n",
    "axes[1].legend(loc='upper left')\n",
    "axes[1].grid()\n",
    "\n",
    "fig.tight_layout();"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
